const app = getApp()
const WXAPI = require('../../wxapi/main')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nickName: null,
    isWaring: false,
    errmsg: '',
    userInfo: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    that.loadUserInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  loadUserInfo: function() {
    let that = this
    let skey = wx.getStorageSync('loginFlag')
    if (skey) {
      WXAPI.loadUser({skey})
      .then(res => {
        console.log('res ', res)
        if (res.code === 0) {
          that.setData({
            userInfo: res.data,
            nickName: res.data.name
          })
        }
      })
    }
  },
  onInput: function(evt) {
    const { value } = evt.detail;
    console.log('va ', value)
    this.setData({
      nickName: value,
      isWaring: false,
    });
  },

  onConfirm: function() {
    let that = this
    if (!that.data.userInfo) {
      wx.showToast({
        title: '尚未登录',
        icon: 'error'
      })
      return
    }
    console.log('current openId ', that.data.userInfo.openId)
    if (!that.data.nickName ||that.data.nickName.length > 20) {
      this.setData({
        isWaring: true,
        errmsg: '昵称格式有误'
      });
      return
    }
    let postData = {key: 'NickName', value: that.data.nickName, openid: that.data.userInfo.openId}
    WXAPI.updateCustom(postData).then(res => {
      console.log('res ', res)
      if (res.code === 0) {      
          wx.showToast({
            title: '更新昵称成功',
            icon: 'success'
          })
          wx.switchTab({
            url: '/pages/my/index',
          })
        
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    })
    
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // let that = this
    // that.loadUserInfo()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})